import { Component } from 'react'
import { Button, Form, Icon, Input, Tooltip } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { Price } from '../../../commons'
import { Item, DeepPartial } from '../type'
import Tags from './tags'

interface Props {
  data: Item
  editing: boolean
  onSubmit: (x: DeepPartial<Item>) => void
  onEdit: () => void
  onDelete: () => void
  onCancel: () => void
}

@(Form.create as any)()
class ItemForm extends Component<Props & FormComponentProps> {
  layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 8 },
  }

  handleSubmit = (event: React.FormEvent<never>) => {
    event.preventDefault()
    const {
      data: { id },
      onSubmit,
      form,
    } = this.props
    const extract = (xs: string[]) => xs.map(x => x.trim()).filter(Boolean)
    const split = (s: string) => s.split(/,|，|\n/)
    const asList = (s = '') => extract(split(s))
    form.validateFieldsAndScroll(
      (error: Error, values: Record<keyof Item, string>) =>
        !error &&
        onSubmit({
          id,
          title: values.title.trim(),
          intro: (values.intro || '').trim(),
          price: Price.read(values.price),
          category: { title: values.category && values.category.trim() },
          tags: asList(values.tags),
          images: asList(values.images),
        }),
    )
  }

  render() {
    return (({ data, editing, onEdit, onDelete, onCancel, form }) => (
      <Form onSubmit={this.handleSubmit}>
        <Form.Item {...this.layout} label="Title">
          {form.getFieldDecorator('title', {
            initialValue: data.title,
            rules: [
              {
                required: true,
                whitespace: true,
                message: 'Please input the title',
              },
            ],
          })(<Input disabled={!editing} />)}
        </Form.Item>
        <Form.Item {...this.layout} label="Intro">
          {form.getFieldDecorator('intro', {
            initialValue: data.intro,
          })(<Input.TextArea autosize disabled={!editing} />)}
        </Form.Item>
        <Form.Item {...this.layout} label="Price">
          {form.getFieldDecorator('price', {
            initialValue: data.price && Price.show(data.price),
            rules: [
              {
                required: true,
                message: 'Please input the price',
              },
              {
                type: 'number',
                transform: Number,
                message: 'The input is not valid price',
              },
            ],
          })(<Input disabled={!editing} />)}
        </Form.Item>
        <Form.Item {...this.layout} label="Category">
          {form.getFieldDecorator('category', {
            initialValue: data.category && data.category.title,
          })(<Input disabled={!editing} />)}
        </Form.Item>
        <Form.Item
          {...this.layout}
          label={
            <span>
              {editing && (
                <Tooltip title="Comma delimited">
                  <Icon type="question-circle-o" />
                </Tooltip>
              )}
              &nbsp;Tags
            </span>
          }
        >
          {!editing ? (
            <Tags data={data.tags} limit={5} />
          ) : (
            form.getFieldDecorator('tags', {
              initialValue: (data.tags || []).join(', '),
            })(<Input disabled={!editing} />)
          )}
        </Form.Item>
        <Form.Item
          {...this.layout}
          label={
            <span>
              {editing && (
                <Tooltip title="Newline delimited">
                  <Icon type="question-circle-o" />
                </Tooltip>
              )}
              &nbsp;Images
            </span>
          }
        >
          {form.getFieldDecorator('images', {
            initialValue: (data.images || []).join('\n'),
          })(<Input.TextArea autosize disabled={!editing} />)}
        </Form.Item>
        <Form.Item wrapperCol={{ offset: this.layout.labelCol.span }}>
          {!editing ? (
            <Button onClick={onEdit}>Edit</Button>
          ) : !data.id ? (
            <Button htmlType="submit">Create</Button>
          ) : (
            <div>
              <Button htmlType="submit">Update</Button>
              <span style={{ margin: '12px' }} />
              <Button onClick={onDelete}>Delete</Button>
              <span style={{ margin: '12px' }} />
              <Button onClick={onCancel}>Cancel</Button>
            </div>
          )}
        </Form.Item>
      </Form>
    ))(this.props)
  }
}

export default (ItemForm as any) as React.ComponentClass<Props>
